<template>
	<div
		style="
			display: flex;
			flex-direction: column;
			justify-content: center;
			margin-top: 20vh;
		"
	>
		<div style="display: flex; align-items: center">
			<div
				style="
					margin-right: 12vw;
					display: flex;
					flex-direction: column;
				"
			>
				<div style="margin-bottom: 1vh">
					<el-text tag="del">原名称</el-text>
				</div>
				<el-input
					v-model="oldNickname"
					style="width: 240px"
					disabled
					:placeholder="oldNickname"
					type="text"
				/>
			</div>
			<div style="display: flex; flex-direction: column">
				<div style="margin-bottom: 1vh">
					<el-text tag="del">取个响亮的大名吧！</el-text>
				</div>
				<el-input
					v-model="nickname"
					style="width: 240px"
					maxlength="8"
					placeholder="请输入"
					show-word-limit
					type="text"
				/>
			</div>
			<div>
				<div style="margin-bottom: 2.5vh"></div>
				<el-text type="danger" size="small"
					>昵称要小于8个字符哦</el-text
				>
			</div>
		</div>
		<el-row style="margin-top: 30vh">
			<el-col :span="24">
				<el-button
					type="success"
					size="large"
					style="width: 100%"
					@click="submitNickname"
					>上传至服务器</el-button
				>
			</el-col>
		</el-row>
	</div>
</template>

<script setup>
import axios from 'axios';
import { onBeforeMount } from 'vue';
import { user } from '../store/user.js';

const userStore = user();

const nickname = ref('');
let oldNickname = ref('');
let username = localStorage.getItem('username');

onBeforeMount(async () => {
	const userData = await userStore.getSpecifyUserMsg(username);
	if (userData.nickname) {
		oldNickname.value = userData.nickname;
	} else {
		oldNickname.value = '您似乎还没有取过名字呢';
	}
});

const submitNickname = async () => {
	if (nickname.value) {
		if (nickname.value.length >= 8) {
			ElNotification({
				title: 'Warning',
				message: '昵称要小于8个字符哦',
				type: 'warning',
			});
			return (nickname.value = '');
		} else {
			try {
				const res = await axios({
					baseURL: 'http://localhost:5000',
					url: '/updateUserNickname',
					method: 'post',
					data: {
						username,
						nickname: nickname.value,
					},
				});
				if (res.data.state === 'ok') {
					ElNotification({
						title: 'Success',
						message: '修改昵称成功！',
						type: 'success',
					});
					return location.reload();
				} else {
					ElNotification({
						title: 'Error',
						message: '修改昵称失败，请检查本地网络',
						type: 'error',
					});
					return location.reload();
				}
			} catch (error) {
				console.log(error);
				ElNotification({
					title: 'Error',
					message: '服务器错误',
					type: 'error',
				});
				return location.reload();
			}
		}
	} else {
		return ElNotification({
			title: 'Warning',
			message: '您还未输入新昵称呢',
			type: 'warning',
		});
	}
};
</script>

<style scoped></style>
